#encoding=utf-8
import xadmin,ujson,time,datetime,traceback
#新页面不是model对应生成的，菜单url配置中的地址对应register_view的
from xadmin.views import BaseAdminPlugin, ModelFormAdminView, ModelAdminView, CommAdminView, csrf_protect_m
from xadmin.util import unquote
from django.utils.html import escape
from django import forms
from xadmin.layout import Fieldset, Main, Side, Row, FormHelper
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _
from django.utils.decorators import method_decorator
from django.http import HttpResponseRedirect
from django.views.decorators.debug import sensitive_post_parameters
from django.conf.urls import patterns, include, url
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect
from django.db.models import Count, Max, F, Q,Min,Sum
import websys.webconfig as webconfig
import websys.fun as fun

from websys.models import (
    ServerInfo,NewInfo,LoginNews
)
from  websys import (
    db_redis
)
from websys.api import InterfaceFun

class TestForm(forms.Form):
    """
    A form used to change the password of a user in the admin interface.
    """
    # error_messages = {
    #     'password_mismatch': _("The two password fields didn't match."),
    # }
    # password1 = forms.CharField(label=_("Password"),
    #                             widget=forms.PasswordInput)
    # password2 = forms.CharField(label=_("Password (again)"),
    #                             widget=forms.PasswordInput)

    def __init__(self,  *args, **kwargs):
        #self.user = user
        super(TestForm, self).__init__(*args, **kwargs)

#缓存平台列表
global PFINFO_LIST
PFINFO_LIST=[]#[{'pf_id':'nhmj123','name':'','games':'1,2,3'},...]
def getPlatformInfo_list():
    global PFINFO_LIST
    if not PFINFO_LIST:
        PFINFO_LIST=ServerInfo.objects.all().values('pf',"name")
getPlatformInfo_list()


#缓存平台列表
global PFINFO_LIST2
PFINFO_LIST2=[]#[{'pf_id':'nhmj123','name':'','games':'1,2,3'},...]
def getPlatformInfo_list2():
    global PFINFO_LIST2
    if not PFINFO_LIST2:
        PFINFO_LIST2=ServerInfo.objects.filter(status=0).values('pf',"name")
getPlatformInfo_list2()
#url对应的标题
URL2TITLE={'bag':'礼包','white':'白名单','server':'开服','chat':'聊天框','news':'公告','blank':'空白页','login_news':'登录公告'}
#自定义的页面
URL2DEFINE=['server','news','login_news']

#金钻消耗统计页面
class CommonSystemView(ModelAdminView):
    model = ServerInfo
    this_form = TestForm
    common_obj={'jstype':'vendor','css_js':('xadmin.form.css','datepicker.css','xadmin.plugins.css', 'xadmin.page.form.js','xadmin.widget.datetime.js')}

    html_obj={}
    for ii in URL2TITLE:
        html_obj[ii]={'title':URL2TITLE[ii]}
        html_obj[ii].update(common_obj)
    #html_obj['share'].update(common_obj)
   # html_obj['table'].update(common_obj)

    # def __init__(self,request):
    #     _title,_tmpurl='金钻消耗统计','diamondreport.html'
    #     self.title=_title
    #     self.tempurl=_tmpurl
    #     print(_title,_tmpurl)

    @csrf_protect_m
    def get(self, request,_type):
        if not self.has_change_permission(request):
            raise 123#PermissionDenied
        self.obj = {}
        self.form = self.this_form()
        #print _type,'--CommonSystemView-'
        self.htmlconfig=self.html_obj[_type]
        _title,_tmpurl=self.htmlconfig['title'],'systemdata/blank.html'
        #if 'isDefine' in self.htmlconfig and self.htmlconfig['isDefine']==1:
        if _type in URL2DEFINE:
            _tmpurl='systemdata/%s.html'%(_type)
        self.title=_title

        self.tempurl=_tmpurl
        global PFINFO_LIST
        global PFINFO_LIST2
        if str(_type) =='server':
            lists=ServerInfo.objects.filter(status=0).values('pf',"name")
            self.htmldata = {'type': _type, 'apps': lists}
        else:
            self.htmldata={'type':_type,'apps':PFINFO_LIST}

        return self.get_response()

    def get_media(self):
        media = super(CommonSystemView, self).get_media()
        if self.htmlconfig['jstype']=='static':
            for ii in self.htmlconfig['css_js']:
                file_type = ii.split('.')[-1]
                if file_type=='css':
                    media.add_css({'screen': [ii]})
                elif file_type=='js':
                    media.add_js((self.static(ii),))
            #tmp_media=self.static(*self.htmlconfig['css_js'])
        else:
            media+=self.vendor(*self.htmlconfig['css_js'])
        media = media+ self.form.media
        return media

    def get_context(self):
        #获取数据
        context = super(CommonSystemView, self).get_context()
        #print(context,'-------------------*****get_context*****',)
        helper = FormHelper()
        helper.form_tag = False
        self.form.helper = helper
        context.update({
            #'title': _('Change password: %s') % escape(unicode(self.obj)),
            'form': self.form,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_view_permission': True,
            'original': self.obj,
            #chong add
            'title':self.title,#_('My Information'),
            'account_view':True,
            'serverval':"服务器上的值",
            'htmldata':self.htmldata
        })
        return context

    #可以按不同的参数加载对应的页面
    def get_response(self):
        #print(self.get_context(),"----******get_response*******",self.admin_site.name)
        return TemplateResponse(self.request, [self.tempurl] , self.get_context(), current_app=self.admin_site.name)
        #return TemplateResponse(self.request, [ self.change_user_password_template or'xadmin/auth/user/change_password.html']
                               # , self.get_context(), current_app=self.admin_site.name)

class DiamondReportView(CommonSystemView):
    def __init__(self):
        super(DiamondReportView,self)#.__init__('金钻消耗统计','diamondreport.html')

class OnlineReportView(CommonSystemView):
    def __init__(self):
        super(OnlineReportView,self)#.__init__('在线统计','onlinereport.html')




#渲染注册请求页面,url配置
# xadmin.site.register_view(r'^core/$', CommonSystemView,name='core_report')#核心数据
# xadmin.site.register_view(r'^recharge/$', CommonSystemView,name='recharge_report')
# xadmin.site.register_view(r'^online/$', CommonSystemView,name='online_report')
# xadmin.site.register_view(r'^props/$', CommonSystemView,name='props_report')
# xadmin.site.register_view(r'^newloss/$', CommonSystemView,name='newloss_report')
# xadmin.site.register_view(r'^loadloss/$', CommonSystemView,name='loadloss_report')
xadmin.site.register_view(r'^systemdata/(.+)/$', CommonSystemView,name='system_%s')#各种按日，月，年汇总页面
#ajax请求页面
urlpatterns = patterns('',
                    #充值报表
                     url(r'^addnews', 'websys.view.systemdata.op_addnews', name='op_addnews'),
                     url(r'^getnews', 'websys.view.systemdata.op_getnews', name='op_getnews'),
                    url(r'^delnews', 'websys.view.systemdata.op_delnews', name='op_delnews'),
                    url(r'^props', 'websys.view.systemdata.op_props', name='op_props'),
                    url(r'^newloss', 'websys.view.systemdata.op_newloss', name='op_newloss'),
                    #url(r'^loadloss', 'websys.view.systemdata.op_loadloss', name='op_loadloss'),
                    url(r'^qu_server', 'websys.view.systemdata.op_quserver', name='op_quserver'),
                    url(r'^ch_server', 'websys.view.systemdata.op_chserver', name='op_chserver'),
                    url(r'^sp_server', 'websys.view.systemdata.op_spserver', name='op_spserver'),
                    url(r'^mz_login_news', 'websys.view.systemdata.mz_login_news', name='mz_login_news'),

    )

#发公告{"title":t_title, "con":t_con,"order":t_order,"pf":t_pf,"date":t0+","+t1}
@csrf_exempt
@login_required(login_url="/xadmin/")
def op_addnews(request):
    ret = {'code':-1,'msg':"err"}
    db_id = request.POST["id"]#id
    s_id = request.POST["pf"]#服
    ser_arr=s_id.split(',')
    s_title = request.POST["title"]
    s_con = request.POST["con"]
    s_order = request.POST["order"]
    s_date_0,s_date_1 = request.POST["date"].split(',')
    #保存到数据库
    if(db_id==''):
        ni=NewInfo()
    else:
        if NewInfo.objects.filter(pk=db_id).exists():
            ni=NewInfo.objects.get(pk=db_id)
        else:
            ret['msg']='数据不存在'
            return HttpResponse(ujson.dumps(ret))

    ni.content=s_con
    ni.title=s_title
    ni.orderid=s_order
    ni.start_time=s_date_0
    ni.end_time=s_date_1
    arr_serinfo=ServerInfo.objects.filter(pf__in=ser_arr)
    ni.save()
    for ii_server in arr_serinfo:
        ni.server.add(ii_server)
    db_id=ni.id
    #提交到游戏服务器
    if InterfaceFun.ADDSCROLLNOTES(ser_arr,s_con,db_id,fun.TimeToStamp(s_date_0+' 00:00:00'),fun.TimeToStamp(s_date_1+' 00:00:00'),int(s_order))==0:
        ret['msg']='通知游戏服失败'
    else:
        ret['msg']=''
    ret['code']=0

    return HttpResponse(ujson.dumps(ret))

#删除
@csrf_exempt
@login_required(login_url="/xadmin/")
def op_delnews(request):
    ret = {'code':-1,'msg':"err"}
    db_id = request.POST["id"]#id
    if db_id.isdigit():
        if NewInfo.objects.filter(pk=db_id).exists():
            ni=NewInfo.objects.get(pk=db_id)
            ser_arr=[]
            tmp_arr=ni.server.all()
            for ii_ser in tmp_arr:
                ser_arr.append(ii_ser.pf)
            if InterfaceFun.DELSCROLLNOTES(ser_arr,db_id):
                ret['code']=0
                ni.delete()
            else:
                ret['msg']='游戏服删除失败'

    return HttpResponse(ujson.dumps(ret))


#公告列表
@csrf_exempt
@login_required(login_url="/xadmin/")
def op_getnews(request):
    ret = []
    arr_ni=NewInfo.objects.all().order_by("-id")
    for ii_ni in arr_ni:
        tmp_ser=''
        #print ii_ni.start_time,type(ii_ni.start_time)
        tmp_obj={'id':ii_ni.id,'title':ii_ni.title,'content':ii_ni.content,'start_time':ii_ni.start_time.strftime('%Y-%m-%d'),
                 'end_time':ii_ni.end_time.strftime('%Y-%m-%d'), 'orderid':ii_ni.orderid,'server':''}
        for ii_ser in ii_ni.server.all():
            if tmp_ser!='':
                tmp_ser+=','
            tmp_ser+=ii_ser.pf
        tmp_obj['server']=tmp_ser
        ret.append(tmp_obj)
    return HttpResponse(ujson.dumps(ret))



@csrf_exempt
@login_required(login_url="/xadmin/")
def op_online(request):
    ret = [{'la_acu':2,'la_pcu':3,'hour':7,'count':8},{'la_acu':2,'la_pcu':3,'hour':10,'count':9}]
    return HttpResponse(ujson.dumps(ret))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_props(request):
    ret = [{'id':2,'name':3,'amount_today':7,'amount_yestoday':8,'amount_trend':2,'amount_average':3,'people_today':7,'people_yestoday':8,'people_trend':2,'people_average':3,'income_today':10,'income_yestoday':9,'income_trend':35,'income_average':88},
           {'id': 2, 'name': 3, 'amount_today': 7, 'amount_yestoday': 8, 'amount_trend': 2, 'amount_average': 3,
            'people_today': 7, 'people_yestoday': 8, 'people_trend': 2, 'people_average': 3, 'income_today': 10,
            'income_yestoday': 9, 'income_trend': 35, 'income_average': 88}]
    return HttpResponse(ujson.dumps(ret))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_newloss(request):
    ret = [{'lead_step':1,'hit_count':2,'loss_count':3,'loss_rate':4,'lead_remain':5},{'lead_step':1,'hit_count':2,'loss_count':3,'loss_rate':4,'lead_remain':5}]
    return HttpResponse(ujson.dumps(ret))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_chserver(request):
    ret = {'ret': -1, 'msg': "err"}
    servers=str(request.POST['pfs'])
    server = servers[:-1].split(',')
    print '--------------',server
    for i in server:
        server_info=ServerInfo.objects.get(pf=i)
        server_info.status=1
        server_info.save()
    ret['ret']=0
    ret['msg']='success'
    return HttpResponse(ujson.dumps(ret))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_quserver(request):
    server_info = ServerInfo.objects.filter(status=1)
    ret=[]
    status_dic={1:'开放'}
    for i in server_info:
        ser_dic={}
        ser_dic['id']=i.id
        ser_dic['pfs']=i.pf
        ser_dic['servername']=i.name
        ser_dic['status']=status_dic[i.status]
        ret.append(ser_dic)
    return HttpResponse(ujson.dumps(ret))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_spserver(request):
    ret = {'ret': -1, 'msg': "err"}
    id=int(request.POST['id'])
    server=ServerInfo.objects.get(id=id)
    server.status=0
    server.save()
    ret['ret']=0
    ret['msg']='success'
    return HttpResponse(ujson.dumps(ret))

@csrf_exempt
@login_required(login_url="/xadmin/")
def mz_login_news(request):
    ret = {'code': -1, 'msg': "err"}
    content = request.POST['content']
    number=LoginNews.objects.all().count()
    print number,'============'
    if int(number)>0:
        login_info=LoginNews.objects.all()[0]
        login_info.content=content
        login_info.save()
        ret['msg'] = '修改成功!'
        ret['code'] = 0
    else:
        loginnew_info = LoginNews()
        loginnew_info.content=content
        loginnew_info.save()
        ret['msg']='修改成功!'
        ret['code']=0

    return HttpResponse(ujson.dumps(ret))
